package kpi.javatraining6.gnatiuk.src.tester.readers;

import kpi.javatraining6.gnatiuk.src.tester.Logger;
import kpi.javatraining6.gnatiuk.src.tester.question.Question;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.util.List;

public class QuestionsSAXParser {
    private static String QUESTIONS_PATH="src/kpi/javatraining6/gnatiuk/src/questionnairs/";
    QuestionSAXHandler handler = new QuestionSAXHandler();
    SAXParser saxParser;
    public QuestionsSAXParser() {
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        try {
            saxParser = saxParserFactory.newSAXParser();
        } catch (ParserConfigurationException | SAXException e) {
            System.out.println("SAX exception");
            Logger.getInstance().recordExceptionalEvent(e);
            System.exit(-2);
        }
    }

    public List<Question> parse(String fileName) {
        InputSource source = new InputSource(QUESTIONS_PATH+fileName);
        try {
            saxParser.parse(source, handler);
        } catch (IOException | SAXException e) {
            System.out.println("IO Exception");
            System.exit(1);
        }
        return handler.getQuestions();
    }

}
